package admin

import (
	"errors"

	"gitee.com/extrame/tujiang/http"
	"gitee.com/extrame/tujiang/http/model"
	"github.com/extrame/goblet"
)

const (
	KeyConfiged = "configed"
)

type System struct {
	goblet.Route `/admin/v1/system`
	Config       *http.Config
	isReady      *bool
}

func (s *System) Ready(ctx *goblet.Context) error {

	if s.isReady != nil {
		if *s.isReady {
			return nil
		} else {
			return http.SystemNotReadyError
		}
	}

	var config model.Config
	has, _ := goblet.DB.Where("key = ?", KeyConfiged).Get(&config)
	if has {
		s.isReady = new(bool)
		*s.isReady = config.Value == "true"
		if *s.isReady {
			return nil
		}
	}
	return http.SystemNotReadyError
}

func (s *System) Init(ctx *goblet.Context, args *model.User) error {

	if s.isReady == nil {
		return errors.New("内部错误：系统没有检查是否初始化")
	} else if *s.isReady {
		return http.SystemIsReadyError
	}

	args.Privilege = model.PrivilegeAdmin
	args.EncryptPassword(s.Config.Salt)
	_, err := goblet.DB.Insert(args)
	if err != nil {
		return err
	}
	return nil
}
